package sk.stuba.fiit.arthur.web.mvc.controller;

import java.util.Collection;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import sk.stuba.fiit.arthur.web.mvc.model.entity.PersonEntity;
import sk.stuba.fiit.arthur.web.mvc.model.service.PersonService;


/**
 * Person controller.
 * 
 * @author Marek Hruska
 */
@Controller
@SessionAttributes(value = {"personEntity"})
public class PersonController {
	
	private static final String LIST_MODEL_KEY = "list";
	private static final String PERSON_ENTITY  = "personEntity";
	
	protected static Logger logger = Logger.getLogger("PersonController"); 
	
	@Autowired()
	private PersonService personService;

	/**
     * <p>Searches for all persons and returns them in a 
     * <code>Collection</code>.</p>
     * 
     * <p>Expected HTTP GET and request '/person/list'.</p>
     */
    @RequestMapping(value="/person/list", method=RequestMethod.GET)
    public @ModelAttribute(LIST_MODEL_KEY) Collection<PersonEntity> getListOfPerson() {
    	logger.debug("Received request to show all persons"); 
    	return personService.findPersons();
    }
    
	/**
     * <p>Create new or update old person 
     * <code>PersonEntity</code>.</p>
     * 
     * <p>Expected HTTP GET and request '/person/form'.</p>
     */
    @RequestMapping(value="/person/form", method=RequestMethod.GET)
    public @ModelAttribute(PERSON_ENTITY) PersonEntity getPersonForm(@RequestParam(value = "id", required = false) Integer id) {
        if(id==null)return new PersonEntity();
        return personService.findPersonById(id);
    }
    
	/**
     * <p>Save new or update old person 
     * <code>PersonEntity</code>.</p>
     * 
     * <p>Expected HTTP POST and response '/person/saveForm'.</p>
     */
    @RequestMapping(value="/person/saveForm", method=RequestMethod.POST)
    public String savePersonForm(PersonEntity personEntity, Model model) {
    	if(personEntity != null) 
    		personService.save(personEntity);
    	return "redirect:/person/list.html";
    }
    
    /**
     * <p>Deletes a person.</p>
     * 
     * <p>Expected HTTP POST and request '/person/delete'.</p>
     */
    @RequestMapping(value="/person/delete", method=RequestMethod.POST)
    public String delete(PersonEntity personEntity) {
    	logger.debug("Received request to delete person with id:"+ personEntity.getId());
        personService.delete(personEntity);
        return "redirect:/person/list.html";
    }
}
